"""
工作流API视图

提供工作流申请、审批等相关API
"""
import json
import logging
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.db import transaction
from django.core.exceptions import ObjectDoesNotExist


from apps.manage.models import Task, WorkflowApprovalNode, AdminUser, AuditRecord, Workflow

logger = logging.getLogger(__name__)

class TaskSubmitView(APIView):
    """
    任务提交视图
    
    提交新的工作流任务
    """
    def post(self, request):
        """
        提交新任务
        
        接收任务表单数据，调用Agent创建任务
        """
        try:
            # 获取请求数据
            data = request.data
            
            # 必要字段检查
            required_fields = ['user_id', 'workflow_id', 'task_name', 'form_data']
            for field in required_fields:
                if field not in data:
                    return Response({
                        "code": 400,
                        "message": f"缺少必要字段: {field}"
                    }, status=status.HTTP_400_BAD_REQUEST)
            
            # 构建Agent指令
            instruction = f"提交任务，数据为: {json.dumps(data)}"
            
            # 调用Agent处理
            result_str = audit_workflow(instruction)
            
            # 解析结果
            try:
                result = json.loads(result_str)
                
                # 如果成功提交
                if result.get("success"):
                    task_id = result.get("task_id")
                    
                    # 分配审批人
                    if task_id:
                        assign_instruction = f"分配审核人，任务id为：{task_id}"
                        assign_result_str = audit_workflow(assign_instruction)
                        
                        try:
                            assign_result = json.loads(assign_result_str)
                            return Response({
                                "code": 200,
                                "message": "任务提交成功并已分配审批人",
                                "data": {
                                    "task_id": task_id,
                                    "approver": assign_result.get("approver_name") if assign_result.get("success") else None
                                }
                            })
                        except (json.JSONDecodeError, AttributeError):
                            # 分配审批人失败，但任务已创建
                            return Response({
                                "code": 200,
                                "message": "任务提交成功，但分配审批人失败",
                                "data": {
                                    "task_id": task_id
                                }
                            })
                    else:
                        return Response({
                            "code": 200,
                            "message": "任务提交成功",
                            "data": result
                        })
                else:
                    # 提交失败
                    return Response({
                        "code": 400,
                        "message": result.get("message", "任务提交失败"),
                        "data": result
                    }, status=status.HTTP_400_BAD_REQUEST)
                    
            except (json.JSONDecodeError, AttributeError):
                # 无法解析Agent返回的结果
                return Response({
                    "code": 500,
                    "message": "Agent返回格式不正确",
                    "data": {
                        "raw_result": result_str
                    }
                }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
                
        except Exception as e:
            logger.error(f"提交任务时出错: {str(e)}")
            return Response({
                "code": 500,
                "message": f"服务器处理请求时出错: {str(e)}"
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class TaskApproveView(APIView):
    """
    任务审批视图
    
    处理任务的审批决策
    """
    def post(self, request):
        """
        审批任务
        
        接收审批决策数据，调用Agent处理审批
        """
        try:
            # 获取请求数据
            data = request.data
            
            # 必要字段检查
            required_fields = ['task_id', 'user_id', 'approval_status']
            for field in required_fields:
                if field not in data:
                    return Response({
                        "code": 400,
                        "message": f"缺少必要字段: {field}"
                    }, status=status.HTTP_400_BAD_REQUEST)
            
            # 验证审批状态值
            if data['approval_status'] not in [1, 2]:
                return Response({
                    "code": 400,
                    "message": "审批状态必须是1(通过)或2(拒绝)"
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 构建Agent指令
            comment = data.get('comment', '')
            approval_text = "同意" if data['approval_status'] == 1 else "拒绝"
            instruction = f"审批人决策，任务id为：{data['task_id']}，审批人id为：{data['user_id']}，决定{approval_text}申请，意见：{comment}"
            
            # 调用Agent处理
            result_str = audit_workflow(instruction)
            
            # 解析结果
            try:
                result = json.loads(result_str)
                
                # 如果成功审批
                if result.get("success"):
                    # 更新任务状态
                    update_instruction = f"更新任务状态，任务id为：{data['task_id']}"
                    update_result_str = audit_workflow(update_instruction)
                    
                    try:
                        update_result = json.loads(update_result_str)
                        return Response({
                            "code": 200,
                            "message": f"任务审批{approval_text}成功",
                            "data": {
                                "task_id": data['task_id'],
                                "record_id": result.get("record_id"),
                                "status_update": update_result
                            }
                        })
                    except (json.JSONDecodeError, AttributeError):
                        # 更新状态失败，但审批已记录
                        return Response({
                            "code": 200,
                            "message": f"任务审批{approval_text}成功，但更新状态失败",
                            "data": {
                                "task_id": data['task_id'],
                                "record_id": result.get("record_id")
                            }
                        })
                else:
                    # 审批失败
                    return Response({
                        "code": 400,
                        "message": result.get("message", "任务审批失败"),
                        "data": result
                    }, status=status.HTTP_400_BAD_REQUEST)
                    
            except (json.JSONDecodeError, AttributeError):
                # 无法解析Agent返回的结果
                return Response({
                    "code": 500,
                    "message": "Agent返回格式不正确",
                    "data": {
                        "raw_result": result_str
                    }
                }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
                
        except Exception as e:
            logger.error(f"审批任务时出错: {str(e)}")
            return Response({
                "code": 500,
                "message": f"服务器处理请求时出错: {str(e)}"
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class TaskInfoView(APIView):
    """
    任务信息视图
    
    获取任务详细信息
    """
    def get(self, request, task_id=None):
        """
        获取任务信息
        
        接收任务ID，返回任务详细信息
        """
        try:
            # 验证任务ID
            if not task_id:
                task_id = request.query_params.get('task_id')
                
            if not task_id:
                return Response({
                    "code": 400,
                    "message": "缺少任务ID参数"
                }, status=status.HTTP_400_BAD_REQUEST)
            
            # 构建Agent指令
            instruction = f"获取任务信息，任务id为：{task_id}"
            
            # 调用Agent处理
            result_str = audit_workflow(instruction)
            
            # 解析结果
            try:
                result = json.loads(result_str)
                
                # 如果成功获取
                if result.get("success"):
                    return Response({
                        "code": 200,
                        "message": "获取任务信息成功",
                        "data": result.get("data")
                    })
                else:
                    # 获取失败
                    return Response({
                        "code": 400,
                        "message": result.get("message", "获取任务信息失败"),
                        "data": result
                    }, status=status.HTTP_400_BAD_REQUEST)
                    
            except (json.JSONDecodeError, AttributeError):
                # 无法解析Agent返回的结果
                return Response({
                    "code": 500,
                    "message": "Agent返回格式不正确",
                    "data": {
                        "raw_result": result_str
                    }
                }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
                
        except Exception as e:
            logger.error(f"获取任务信息时出错: {str(e)}")
            return Response({
                "code": 500,
                "message": f"服务器处理请求时出错: {str(e)}"
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class AgentMonitorView(APIView):
    """
    Agent监控视图
    
    获取Agent调用统计信息
    """
    def get(self, request):
        """获取Agent监控数据"""
        try:
            monitor_data = get_monitor_data()
            return Response({
                "code": 200,
                "message": "获取监控数据成功",
                "data": monitor_data
            })
        except Exception as e:
            logger.error(f"获取Agent监控数据时出错: {str(e)}")
            return Response({
                "code": 500,
                "message": f"服务器处理请求时出错: {str(e)}"
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    def delete(self, request):
        """重置Agent监控数据"""
        try:
            result = reset_monitor_data()
            return Response({
                "code": 200,
                "message": "重置监控数据成功",
                "data": result
            })
        except Exception as e:
            logger.error(f"重置Agent监控数据时出错: {str(e)}")
            return Response({
                "code": 500,
                "message": f"服务器处理请求时出错: {str(e)}"
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR) 